package threadutils;

import java.util.concurrent.atomic.AtomicBoolean;

public final class IncrementalThread extends Thread {

    private final Runnable mTask;

    private final AtomicBoolean mIncrement;

    private final AtomicBoolean mStopRunning;

    public IncrementalThread(Runnable task) {
        mTask = task;
        mIncrement = new AtomicBoolean(false);
        mStopRunning = new AtomicBoolean(false);
    }

    public boolean increment() {
        if (mIncrement.getAndSet(true)) {
            return false;
        }
        notify();
        return true;
    }

    public boolean stopRunning() {
        if (mIncrement.getAndSet(true)) {
            return false;
        }

        mStopRunning.set(true);
        notify();
        return true;
    }

    @Override
    public void run() {
        while (true) {
            while (true) {
                cleanWait();
                if (mIncrement.get()) {
                    break;
                }
            }

            if (mStopRunning.get()) {
                return;
            }

            mTask.run();
            mIncrement.set(false);
        }
    }

    private void cleanWait() {
        try {
            this.wait();
        } catch (InterruptedException ex) {}
    }
}
